package com.wardrobe.handler;

import org.apache.shiro.crypto.hash.Sha512Hash;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

public class CodeHelper {

    public static String encodePwd(String password) {
        String encodedPassword = new Sha512Hash(password).toBase64();
        return encodedPassword;
    }

    public static String encodePwdForMd5(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
            // 得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer buffer = new StringBuffer();
            // 把每一个byte 做一个与运算 0xff;
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;// 加盐
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }
            // 标准的md5加密后的结果
            return buffer.toString();
    }

    private static String sha256HMAC(String message, String secret) throws Exception {
        String hash = "";
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
        hash = byteArrayToHexString(bytes);
        System.out.println(hash);
        return hash;
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    public static Integer[] intArrToIntegerArr(int[] arr) {
        Integer[] ret = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) {
            ret[i] = arr[i];
        }
        return ret;
    }

    public static String getItemsByList(List<Map<String,Object>> list){
        StringBuffer temp = new StringBuffer();
        for (Map<String,Object> row: list){
//            String itemId = BaseUtils.getStringValueFromMap(row, "item_id");
            temp =temp.append("itemId"+",");
        }
        return temp.length()>0? temp.toString().substring(0, temp.toString().length() - 1):"-1";
    }

}
